package com.lnj.community.service.Impl;


import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.lnj.community.dao.entity.DiscussPost;
import com.lnj.community.mapper.DiscussPostMapper;
import com.lnj.community.service.DiscussPostService;
import com.lnj.community.utiles.SensitiveUtile;
import io.micrometer.common.lang.NonNull;
import jakarta.annotation.Nullable;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DiscussPostServiceImpl implements DiscussPostService {
    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(DiscussPostServiceImpl.class);
    private DiscussPostMapper discussPostMapper;
    private SensitiveUtile sensitiveUtile;
    private Cache<String, List<DiscussPost>> postListCache;
    private Cache<String, Integer> postRowsCache;
    private RedisTemplate redisTemplate;

    public DiscussPostServiceImpl(DiscussPostMapper discussPostMapper, SensitiveUtile sensitiveUtile,RedisTemplate redisTemplate,
                                  Cache<String, List<DiscussPost>> postListCache, Cache<String, Integer> postRowsCache) {
        this.discussPostMapper = discussPostMapper;
        this.sensitiveUtile = sensitiveUtile;
        this.postListCache = postListCache;
        this.postRowsCache = postRowsCache;
        this.redisTemplate = redisTemplate;
    }

    //查找帖子列表
    @Override
    public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit,int orderMode) {
        if (userId == 0 && orderMode == 1) {
            String cacheKey = "postList:" + offset + ":" + limit;
            //存数据到缓存中
            return  postListCache.get(cacheKey,key->{
                if (key == null || key.length() == 0) {
                    throw new IllegalArgumentException("参数错误!");
                }
                //先判断Redis中是否有数据
                ValueOperations<String, List<DiscussPost>> ops = redisTemplate.opsForValue();
                List<DiscussPost> postList = (List<DiscussPost>) ops.get(key);
                if (postList != null) {
                    logger.debug("load post list from Redis.");
                    return postList;
                }

                String[] params = key.split(":");
                if (params == null || params.length != 3) {
                    throw new IllegalArgumentException("参数错误!");
                }

                int start = Integer.valueOf(params[1]);
                int end = Integer.valueOf(params[2]);
                List<DiscussPost> discussPosts = discussPostMapper.selectDiscussPosts(0, start, end, 1);
                // 将数据存入 Redis
                if (discussPosts!= null) {
                    ops.set(key, discussPosts, 600, TimeUnit.SECONDS);
                }
                logger.debug("load post list from DB.");
                return discussPosts;
            });
        }
        logger.debug("load post list from DB.");
        List<DiscussPost> discussPosts = discussPostMapper.selectDiscussPosts(userId, offset, limit, orderMode);

        return discussPostMapper.selectDiscussPosts(userId, offset, limit,orderMode);
    }

    //查找帖子行数
    @Override
    public int findDiscussPostRows(int userId) {
        if (userId == 0) {
            String cacheKey = "postRows:" + userId;
            return (int) postRowsCache.get(cacheKey,key->{
                if (key == null || key.length() == 0) {
                    throw new IllegalArgumentException("参数错误!");
                }
                //先判断Redis中是否有数据
                ValueOperations<String, Integer> ops = redisTemplate.opsForValue();
                Integer rows = (Integer) ops.get(key);
                if (rows!= null) {
                    logger.debug("load post rows from Redis.");
                    return rows;
                }
                String[] params = key.split(":");
                if (params == null || params.length!= 2) {
                    throw new IllegalArgumentException("参数错误!");
                }
                int userId1 = Integer.valueOf(params[1]);
                int row = discussPostMapper.selectDiscussPostRows(userId1);
                // 将数据存入 Redis
                if (row>= 0) {
                    ops.set(key, row, 600, TimeUnit.SECONDS);
                }
                logger.debug("load post rows from DB.");
                return row;
            });
        }
        logger.debug("load post rows from DB.");
        return discussPostMapper.selectDiscussPostRows(userId);
    }

    @Override
    public int addDiscussPost(DiscussPost post) {
        if (post == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }
        // 转义HTML标记
        post.setContent(HtmlUtils.htmlEscape(post.getContent()));
        post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));

        // 过滤敏感词
        post.setContent(sensitiveUtile.filter(post.getContent()));
        post.setTitle(sensitiveUtile.filter(post.getTitle()));

        return discussPostMapper.insertDiscussPost(post);
    }

    @Override
    public DiscussPost findDiscussPostById(int id) {
        return discussPostMapper.selectDiscussPostById(id);
    }

    @Override
    public int updateCommentCount(int id, int commentCount) {
        return discussPostMapper.updateCommentCount(id, commentCount);
    }

    @Override
    public int updateType(int id, int type) {
        return discussPostMapper.updateType(id, type);
    }

    @Override
    public int updateStatus(int id, int status) {
        return discussPostMapper.updateStatus(id, status);
    }

    @Override
    public void updateScore(int postId, double score) {
        discussPostMapper.updateScore(postId, score);
    }

}
